package com.molichuxing.gateway.api.config;

import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;

public class ObjectMapperConfig extends ObjectMapper {
	private static final long serialVersionUID = 1L;

	static class BooleanSerializer extends JsonSerializer<Boolean> {
		@Override
		public void serialize(Boolean value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
			if (value != null && value) {
				gen.writeNumber(1);
			} else {
				gen.writeNumber(0);
			}
		}
	}

	public ObjectMapperConfig() {
		super();
		SimpleModule module = new SimpleModule();
		module.addSerializer(Long.class, ToStringSerializer.instance);
		module.addSerializer(Long.TYPE, ToStringSerializer.instance);
		module.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
		module.addSerializer(LocalTime.class,
				new LocalTimeSerializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
		module.addSerializer(LocalDateTime.class,
				new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
		// boolean转换0/1
		BooleanSerializer serialize = new BooleanSerializer();
		module.addSerializer(Boolean.class, serialize);
		module.addSerializer(boolean.class, serialize);
		this.registerModule(module);
	}
}
